#include <regx52.h>
#include "DS1302_Time.h"

//typedef struct Time Time;

Time time={20,0,0,0,0,0,1};


sbit Time_SCLK = P3 ^ 6;
sbit Time_IO = P3 ^ 4;
sbit Time_CE = P3 ^ 5;

#define Time_Second 0x80
#define Time_Minute 0x82
#define Time_Hour 0x84
#define Time_Day 0x86
#define Time_Month 0x88
#define Time_Week 0x8a
#define Time_Year 0x8c
#define WP 0x8e





void DS1302_Write(unsigned char Command, unsigned char Data)//向时钟芯片写入数据，用于设置时间
{
    unsigned char i = 0;
    Time_CE = 1;
    for (i = 0; i < 8; i++)
    {
        Time_IO = Command & (0x01 << i);
        Time_SCLK = 1;
        Time_SCLK = 0;
    }
    for (i = 0; i < 8; i++)
    {
        Time_IO = Data & (0x01 << i);
        Time_SCLK = 1;
        Time_SCLK = 0;
    }
    Time_CE = 0;
}



unsigned char DS1302_Read(unsigned char Command)//从时钟芯片读取数据，用于显示时间
{
    unsigned char i = 0;
    unsigned char Data = 0;
    Command |= 0x01;
    Time_CE = 1;
    for (i = 0; i < 8; i++)
    {
        Time_IO = Command & (0x01 << i);
        Time_SCLK = 0;
        Time_SCLK = 1;
    }
    for (i = 0; i < 8; i++)
    {
        Time_SCLK = 1;
        Time_SCLK = 0;
        if (Time_IO == 1)
        {
            Data |= (0x01 << i);
        }
    }
    Time_IO = 0;

    Time_CE = 0;
    return Data;
}



void DS1302_Init()
{
    Time_CE = 0;
    Time_SCLK = 0;
    DS1302_Write(WP,0x00);
}



void DS1302_SetTime()//设置时间
{
    DS1302_Write(Time_Year,time.Year/10*16+time.Year%10);
    DS1302_Write(Time_Month,time.Month/10*16+time.Month%10);
    DS1302_Write(Time_Day,time.Day/10*16+time.Day%10);
    DS1302_Write(Time_Hour,time.Hour/10*16+time.Hour%10);
    DS1302_Write(Time_Minute,time.Minute/10*16+time.Minute%10);
    DS1302_Write(Time_Second,time.Second/10*16+time.Second%10);
    DS1302_Write(Time_Week,time.Weekday);
}



void DS1302_Showtime()//显示时间
{
    time.Year=DS1302_Read(Time_Year)/16*10+DS1302_Read(Time_Year)%16;
    time.Month=DS1302_Read(Time_Month)/16*10+DS1302_Read(Time_Month)%16;
    time.Day=DS1302_Read(Time_Day)/16*10+DS1302_Read(Time_Day)%16;
    time.Hour=DS1302_Read(Time_Hour)/16*10+DS1302_Read(Time_Hour)%16;
    time.Minute=DS1302_Read(Time_Minute)/16*10+DS1302_Read(Time_Minute)%16;
    time.Second=DS1302_Read(Time_Second)/16*10+DS1302_Read(Time_Second)%16;
    time.Weekday=DS1302_Read(Time_Week)/16*10+DS1302_Read(Time_Week)%16;
}